package com.dlb.andorid.activity;

import android.app.Dialog;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.dlb.andorid.App;
import com.dlb.andorid.R;
import com.dlb.andorid.XContract;
import com.dlb.andorid.XServerMsg;
import com.dlb.andorid.bean.AddressRetrieval;
import com.dlb.andorid.bean.Area;
import com.dlb.andorid.bean.ArgMerchantReg;
import com.dlb.andorid.bean.City;
import com.dlb.andorid.bean.MerchantType;
import com.dlb.andorid.bean.Province;
import com.dlb.andorid.presenter.ShrzPresenter;
import com.kwan.xframe.mvp.presenter.BasePresenter;
import com.kwan.xframe.mvp.view.activity.BaseCommonActivity;
import com.kwan.xframe.util.DialogFactory;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.Glide4Engine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.listener.OnCheckedListener;
import com.zhihu.matisse.listener.OnSelectedListener;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.dlb.andorid.presenter.LoginPresenter.CODE_TYPE_NORMAL;

public class SHRZActivity extends BaseCommonActivity implements XContract.IShrzView {

	private View ll_yyzz_click, ll_yyzz, ll_sfz1_click, ll_sfz1,ll_shmc, ll_sfz2_click, ll_sfz2, ll_merchant_type, ll_shop_pic_click, ll_shop_pic;
	private ImageView iv_yyzz, iv_sfz1, iv_sfz2, iv_shop_pic;
	private TextView tv_province, tv_city, tv_area, tv_type, tv_search;
	private View ll_province, ll_city, ll_area, tv_submit, ll_search;
	private EditText et_phone, et_code, et_name, et_real_name, et_address;
	private TextView tv_send_code;
	private ShrzPresenter mPresenter;

	public static final int REG_TYPE_MERCHANT = 1;
	public static final int REG_TYPE_RIDER = 2;

	public int REG_TYPE;

	@Override
	protected void beForeSetContentView() {
		super.beForeSetContentView();
		REG_TYPE = (int) getIntentData("type");
	}

	@Override
	protected BasePresenter getBasePresenter() {
		mPresenter = new ShrzPresenter(this);
		return mPresenter;
	}

	@Override
	protected void initViews() {
		super.initViews();

		ll_shmc= findViewById(R.id.ll_shmc);
		et_address = findViewById(R.id.et_address);
		tv_search = findViewById(R.id.tv_search);
		ll_search = findViewById(R.id.ll_search);

		et_name = findViewById(R.id.et_name);
		et_phone = findViewById(R.id.et_phone);
		et_code = findViewById(R.id.et_code);
		et_real_name = findViewById(R.id.et_real_name);
		tv_send_code = findViewById(R.id.tv_send_code);

		tv_type = findViewById(R.id.tv_type);
		ll_merchant_type = findViewById(R.id.ll_merchant_type);
		tv_submit = findViewById(R.id.tv_submit);
		tv_province = findViewById(R.id.tv_province);
		tv_city = findViewById(R.id.tv_city);
		tv_area = findViewById(R.id.tv_area);


		ll_province = findViewById(R.id.ll_province);
		ll_city = findViewById(R.id.ll_city);
		ll_area = findViewById(R.id.ll_area);

		ll_shop_pic_click = findViewById(R.id.ll_shop_pic_click);
		ll_shop_pic = findViewById(R.id.ll_shop_pic);
		iv_shop_pic = findViewById(R.id.iv_shop_pic);

		ll_yyzz_click = findViewById(R.id.ll_yyzz_click);
		ll_yyzz = findViewById(R.id.ll_yyzz);
		iv_yyzz = findViewById(R.id.iv_yyzz);

		ll_sfz1_click = findViewById(R.id.ll_sfz1_click);
		ll_sfz1 = findViewById(R.id.ll_sfz1);
		ll_sfz2_click = findViewById(R.id.ll_sfz2_click);
		ll_sfz2 = findViewById(R.id.ll_sfz2);

		iv_sfz1 = findViewById(R.id.iv_sfz1);
		iv_sfz2 = findViewById(R.id.iv_sfz2);

		ll_yyzz_click.setOnClickListener(this);
		ll_sfz1_click.setOnClickListener(this);
		ll_sfz2_click.setOnClickListener(this);

		ll_shop_pic_click.setOnClickListener(this);

		ll_province.setOnClickListener(this);
		ll_city.setOnClickListener(this);
		ll_area.setOnClickListener(this);
		ll_merchant_type.setOnClickListener(this);
		tv_send_code.setOnClickListener(this);
		tv_submit.setOnClickListener(this);
		ll_search.setOnClickListener(this);

		mMerchantTypeAdapter = new BaseQuickAdapter<MerchantType, BaseViewHolder>(R.layout.list_item_string, mMerchantTypes) {
			@Override
			protected void convert(BaseViewHolder helper, MerchantType item) {
				helper.setText(R.id.tv_name, item.getMerchant_type_name());
			}
		};

		mMerchantTypeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
			@Override
			public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

				mMerchantType = mMerchantTypes.get(position);
				tv_type.setText(mMerchantType.getMerchant_type_name());
				dialog.dismiss();
			}
		});


		if (REG_TYPE == REG_TYPE_RIDER) {
			ll_shop_pic_click.setVisibility(View.GONE);
			ll_yyzz_click.setVisibility(View.GONE);
			ll_merchant_type.setVisibility(View.GONE);
			ll_shmc.setVisibility(View.GONE);
		}

	}

	Province mProvince;
	City mCity;
	Area mArea;
	AddressRetrieval mRetrieval;
	MerchantType mMerchantType;

	List<Province> mProvinces;
	List<City> mCitys;
	List<Area> mAreas;
	//List<AddressRetrieval> mAddressRetrievals = new ArrayList<>();
	List<MerchantType> mMerchantTypes = new ArrayList<>();

	BaseQuickAdapter<Province, BaseViewHolder> mProviceAdapter;
	BaseQuickAdapter<City, BaseViewHolder> mCityAdapter;
	BaseQuickAdapter<Area, BaseViewHolder> mAreaAdapter;
	//BaseQuickAdapter<AddressRetrieval, BaseViewHolder> mAddressRetrievalAdapter;
	BaseQuickAdapter<MerchantType, BaseViewHolder> mMerchantTypeAdapter;


	void setCityText() {

		tv_province.setText(mProvince.getProvince_name());
		tv_city.setText(mCity.getCity_name());
		tv_area.setText(mArea.getArea_name());

		tv_search.setText("");
		mRetrieval = null;

	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		if (v == ll_yyzz_click) {
			selectImage(REQUEST_CODE_CHOOSE_YYZZ);
		} else if (v == ll_sfz1_click) {
			selectImage(REQUEST_CODE_CHOOSE_SFZ1);
		} else if (v == ll_sfz2_click) {
			selectImage(REQUEST_CODE_CHOOSE_SFZ2);
		} else if (v == ll_shop_pic_click) {
			selectImage(REQUEST_CODE_CHOOSE_SHOP);
		} else if (v == ll_province) {
			showDialog(mProviceAdapter);
		} else if (v == ll_city) {
			showDialog(mCityAdapter);
		} else if (v == ll_area) {
			showDialog(mAreaAdapter);
		} else if (v == ll_search) {

			Bundle bundle = new Bundle();
			bundle.putLong("province_id", mProvince.getProvince_id());
			bundle.putLong("city_id", mCity.getCity_id());
			bundle.putLong("area_id", mArea.getArea_id());
			go2ActivityForResult(AddressSearchActivity.class, 100, bundle, 0, 0);


//			String key;
//			key = et_key.getText().toString();
//			if (key.isEmpty())
//				key = "";
//
//			showProgress("");
//			mPresenter.getAddressRetrieval(mProvince.getProvince_id(), mCity.getCity_id(), mArea.getArea_id(), key);

		} else if (v == ll_merchant_type) {
			if (mMerchantTypes.size() == 0) {
				showProgress("");
				mPresenter.getMerchantType();
			} else {
				showDialog(mMerchantTypeAdapter);
			}

		} else if (v == tv_send_code) {

			String strPhone = et_phone.getText().toString();
			if (strPhone.isEmpty()) {
				toastMsg("请输入手机号码");
			} else {
				showProgress("");
				mPresenter.getCode(strPhone, CODE_TYPE_NORMAL);
			}

		} else if (v == tv_submit) {
			submit();
		}
	}

	private void submit() {

		if (checkForm()) {

			ArgMerchantReg arg = new ArgMerchantReg(App.mUserInfo.getUser_id(), mStrPhone,
					mStrBase64SHOP, mStrCode, mStrName, mStrRealName,
					mStrBase64YYZZ, mStrBase64SFZ1, mStrBase64SFZ2,
					mMerchantType.getMerchant_type_id(),
					mProvince.getProvince_id(),
					mCity.getCity_id(),
					mArea.getArea_id(),
					et_address.getText().toString(),
					mRetrieval.getLongitude(),
					mRetrieval.getLatitude());

			showProgress("");

			if (REG_TYPE == REG_TYPE_MERCHANT)
				mPresenter.regMerchant(arg);
			else
				mPresenter.regRider(arg);
		}


	}

	String mStrName, mStrPhone, mStrCode, mStrRealName;

	public boolean checkForm() {

		mStrName = et_name.getText().toString();
		if (mStrName.isEmpty()) {
			toastMsg("请填写名称");
			return false;
		}

		mStrPhone = et_phone.getText().toString();
		if (mStrPhone.isEmpty()) {
			toastMsg("请填写手机号码");
			return false;
		}

		mStrCode = et_code.getText().toString();
		if (mStrCode.isEmpty()) {
			toastMsg("请填写验证码");
			return false;
		}

		mStrRealName = et_real_name.getText().toString();
		if (mStrRealName.isEmpty()) {
			toastMsg("请填姓名");
			return false;
		}

		if (mProvince == null) {
			toastMsg("请选择省");
			return false;
		}

		if (mCity == null) {
			toastMsg("请选择市");
			return false;
		}

		if (mArea == null) {
			toastMsg("请选择区");
			return false;
		}

		if (mRetrieval == null) {
			toastMsg("请选择地址");
			return false;
		}

		if (mMerchantType == null && REG_TYPE == REG_TYPE_MERCHANT) {
			toastMsg("请选择商户类型");
			return false;
		}
		if (mStrBase64SHOP.isEmpty() && REG_TYPE == REG_TYPE_MERCHANT) {
			toastMsg("请选择门头图片");
			return false;
		}
		if (mStrBase64YYZZ.isEmpty() && REG_TYPE == REG_TYPE_MERCHANT) {
			toastMsg("请选择营业执照");
			return false;
		}
		if (mStrBase64SFZ1.isEmpty()) {
			toastMsg("请选择身份证正面");
			return false;
		}
		if (mStrBase64SFZ2.isEmpty()) {
			toastMsg("请选择身份证反面");
			return false;
		}

		return true;
	}


	void selectImage(int code) {
		Matisse.from(SHRZActivity.this)
				.choose(MimeType.ofImage(), false)
				.countable(true)
				.showSingleMediaType(true)
				//.capture(true)
				.captureStrategy(
						new CaptureStrategy(true, "com.dlb.andorid.fileprovider", "test"))
				.maxSelectable(1)
				//.addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
				.theme(R.style.Matisse_Dracula)
				.gridExpectedSize(
						getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
				.restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
				.thumbnailScale(0.85f)
				//.imageEngine(new PicassoEngine())
				.imageEngine(new Glide4Engine())    // for glide-V4
				.setOnSelectedListener(new OnSelectedListener() {
					@Override
					public void onSelected(
							@NonNull List<Uri> uriList, @NonNull List<String> pathList) {
						// DO SOMETHING IMMEDIATELY HERE
						Log.e("onSelected", "onSelected: pathList=" + pathList);

					}
				})
				.originalEnable(true)
				.maxOriginalSize(10)
				.autoHideToolbarOnSingleTap(true)
				.setOnCheckedListener(new OnCheckedListener() {
					@Override
					public void onCheck(boolean isChecked) {
						// DO SOMETHING IMMEDIATELY HERE
						Log.e("isChecked", "onCheck: isChecked=" + isChecked);
					}
				})
				.forResult(code);
	}

	int REQUEST_CODE_CHOOSE_YYZZ = 101;
	int REQUEST_CODE_CHOOSE_SFZ1 = 102;
	int REQUEST_CODE_CHOOSE_SFZ2 = 103;
	int REQUEST_CODE_CHOOSE_SHOP = 104;

	String mStrBase64YYZZ = "";
	String mStrBase64SFZ1 = "";
	String mStrBase64SFZ2 = "";
	String mStrBase64SHOP = "";

	public String Bitmap2StrByBase64(Bitmap bit) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		bit.compress(Bitmap.CompressFormat.JPEG, 40, bos);//参数100表示不压缩
		byte[] bytes = bos.toByteArray();
		return Base64.encodeToString(bytes, Base64.DEFAULT);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);


		if (resultCode == RESULT_OK)

			if (requestCode == REQUEST_CODE_CHOOSE_YYZZ || requestCode == REQUEST_CODE_CHOOSE_SFZ1 || requestCode == REQUEST_CODE_CHOOSE_SFZ2 || requestCode == REQUEST_CODE_CHOOSE_SHOP) {
				String path = Matisse.obtainPathResult(data).get(0);
				Log.d("Matisse", "mSelected: " + path);

				if (requestCode == REQUEST_CODE_CHOOSE_YYZZ) {

					mImageLoader.loadFile(new File(path), iv_yyzz);
					iv_yyzz.setVisibility(View.VISIBLE);
					ll_yyzz.setVisibility(View.INVISIBLE);
					mStrBase64YYZZ = Bitmap2StrByBase64(BitmapFactory.decodeFile(path));
					Log.d("Matisse", "mSelected: " + mStrBase64YYZZ);

				} else if (requestCode == REQUEST_CODE_CHOOSE_SFZ1) {

					mImageLoader.loadFile(new File(path), iv_sfz1);
					iv_sfz1.setVisibility(View.VISIBLE);
					ll_sfz1.setVisibility(View.INVISIBLE);
					mStrBase64SFZ1 = Bitmap2StrByBase64(BitmapFactory.decodeFile(path));

				} else if (requestCode == REQUEST_CODE_CHOOSE_SFZ2) {

					mImageLoader.loadFile(new File(path), iv_sfz2);
					iv_sfz2.setVisibility(View.VISIBLE);
					ll_sfz2.setVisibility(View.INVISIBLE);
					mStrBase64SFZ2 = Bitmap2StrByBase64(BitmapFactory.decodeFile(path));
				} else if (requestCode == REQUEST_CODE_CHOOSE_SHOP) {
					mImageLoader.loadFile(new File(path), iv_shop_pic);
					iv_shop_pic.setVisibility(View.VISIBLE);
					ll_shop_pic.setVisibility(View.INVISIBLE);
					mStrBase64SHOP = Bitmap2StrByBase64(BitmapFactory.decodeFile(path));
				}
			} else if (requestCode == 100) {

				mRetrieval = (AddressRetrieval) data.getSerializableExtra("data");
				tv_search.setText(mRetrieval.getName());
			}
	}

	@Override
	protected void initData() {
		showProgress("");
		mPresenter.getCity();
	}

	@Override
	protected int getTopViewId() {
		return 0;
	}

	@Override
	protected int getMainViewId() {
		return R.layout.activity_shrz;
	}

	@Override
	protected int getBottomViewId() {
		return 0;
	}

	@Override
	protected String getTitleTxt() {
		if (REG_TYPE == REG_TYPE_MERCHANT)
			return "商户入驻";
		else
			return "配送员入驻";
	}

	@Override
	public String getPageName() {
		return null;
	}

	@Override
	public void getMerchantTypeListSuccess(List<MerchantType> data) {

		dismissProgress();

		mMerchantTypes.clear();
		mMerchantTypes.addAll(data);
		mMerchantTypeAdapter.setNewData(mMerchantTypes);

		showDialog(mMerchantTypeAdapter);

	}

	@Override
	public void getAddressCitySuccess(List<Province> data) {
		dismissProgress();
		mProvinces = data;

		mProvince = mProvinces.get(0);

		mCitys = mProvince.getCity();
		mCity = mCitys.get(0);

		mAreas = mCity.getArea();
		mArea = mAreas.get(0);

		setCityText();


		mProviceAdapter = new BaseQuickAdapter<Province, BaseViewHolder>(R.layout.list_item_string, mProvinces) {
			@Override
			protected void convert(BaseViewHolder helper, Province item) {
				helper.setText(R.id.tv_name, item.getProvince_name());
			}
		};

		mProviceAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
			@Override
			public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

				mProvince = mProvinces.get(position);
				mCity = mProvince.getCity().get(0);
				mArea = mCity.getArea().get(0);
				mCityAdapter.setNewData(mCitys);
				mAreaAdapter.setNewData(mAreas);
				setCityText();
				dialog.dismiss();
			}
		});

		mCityAdapter = new BaseQuickAdapter<City, BaseViewHolder>(R.layout.list_item_string, mCitys) {
			@Override
			protected void convert(BaseViewHolder helper, City item) {
				helper.setText(R.id.tv_name, item.getCity_name());
			}
		};

		mCityAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
			@Override
			public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
				mCity = mCitys.get(position);
				mAreas = mCity.getArea();
				mArea = mAreas.get(0);
				mAreaAdapter.setNewData(mAreas);
				setCityText();
				dialog.dismiss();
			}
		});

		mAreaAdapter = new BaseQuickAdapter<Area, BaseViewHolder>(R.layout.list_item_string, mAreas) {
			@Override
			protected void convert(BaseViewHolder helper, Area item) {
				helper.setText(R.id.tv_name, item.getArea_name());
			}
		};

		mAreaAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
			@Override
			public void onItemClick(BaseQuickAdapter adapter, View view, int position) {

				mArea = mAreas.get(position);
				setCityText();
				dialog.dismiss();

			}
		});


	}

	@Override
	public void getAddressRetrievalSuccess(List<AddressRetrieval> data) {

	}

	@Override
	public void regMerchantSuccess(XServerMsg data) {
		dismissProgress();
		toastMsg(data.getMsg());
	}

	@Override
	public void getCodeSuccess(String msg) {
		dismissProgress();
		toastMsg(msg);
	}

	Dialog dialog;

	private void showDialog(BaseQuickAdapter adapter) {
		View view = getLayoutInflater().inflate(R.layout.layout_dialog_list, null);
		dialog = DialogFactory.showCustomDialog3(this, view);
		RecyclerView recyclerView = view.findViewById(R.id.recycleView);

		recyclerView.setLayoutManager(new LinearLayoutManager(this));
		recyclerView.setItemAnimator(new DefaultItemAnimator());

		recyclerView.setHasFixedSize(true);
		recyclerView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
		recyclerView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

		recyclerView.setAdapter(adapter);

		dialog.show();
	}
}
